package com.js.rtu.fragment.first;

import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;

import androidx.appcompat.widget.AppCompatImageView;

import com.js.rtu.R;
import com.js.rtu.base.BaseFragment;
import com.js.rtu.event.StartBrotherEvent;
import com.js.rtu.fragment.QrCodeInfo;
import com.xuexiang.xqrcode.XQRCode;
import com.xuexiang.xqrcode.camera.CameraManager;
import com.xuexiang.xqrcode.ui.CaptureActivity;
import com.xuexiang.xqrcode.ui.CaptureFragment;
import com.xuexiang.xqrcode.util.QRCodeAnalyzeUtils;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 扫一扫
 * Created by wz on 2020/4/26.
 */
public class QRCodeFragment extends BaseFragment {

    @BindView(R.id.iv_flash_light)
    AppCompatImageView ivFlashLight;
    private boolean mIsOpen;


    public static QRCodeFragment newInstance() {

        Bundle args = new Bundle();
        QRCodeFragment fragment = new QRCodeFragment();
        fragment.setArguments(args);
        return fragment;
    }



    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tab_first_qrcode;
    }

    @Override
    protected void initView() {
        // 为二维码扫描界面设置定制化界面
//            mvpPresenter.getData();
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        CaptureFragment captureFragment = XQRCode.getCaptureFragment(R.layout.layout_custom_camera);
        captureFragment.setAnalyzeCallback(analyzeCallback);
        captureFragment.setCameraInitCallBack(e -> {
            if (e != null) {
                CaptureActivity.showNoPermissionTip(getActivity(), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        _mActivity.onBackPressed();
                    }
                });
            } else {
                mIsOpen = XQRCode.isFlashLightOpen();
            }
        });
        getChildFragmentManager().beginTransaction().replace(R.id.fl_my_container, captureFragment).commit();
    }



    /**
     * 二维码解析回调函数
     */
    private QRCodeAnalyzeUtils.AnalyzeCallback analyzeCallback = new QRCodeAnalyzeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
            if (result.contains(",")) {
                String[] data = result.split(",");
                if (data.length == 12) {
                    QrCodeInfo        info = new QrCodeInfo(data[0], data[1], data[2], data[3], data[4],
                            data[5], data[6], data[7], data[8], data[9], data[10], data[11]);

                    EventBus.getDefault().post(new StartBrotherEvent(QRResultFragment.newInstance(info.getMac())));
                }
            }
            Log.e("xxxxxxx",result);
//            QrCodeInfo info = new Gson().fromJson(result, QrCodeInfo.class);

//            EventBus.getDefault().post(result);


        }

        @Override
        public void onAnalyzeFailed() {

        }
    };


    @OnClick({R.id.iv_flash_light, R.id.iv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_flash_light:
                switchFlashLight();
                break;
            case R.id.iv_back:
                _mActivity.onBackPressed();
                break;
        }
    }
    private void switchFlashLight() {
        mIsOpen = !mIsOpen;
        try {
            XQRCode.switchFlashLight(mIsOpen);
            if (mIsOpen) {
                ivFlashLight.setImageResource(R.drawable.ic_flash_light_open);
            } else {
                ivFlashLight.setImageResource(R.drawable.ic_flash_light_close);
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            toastShow("设备不支持闪光灯!");
        }
    }

    /**
     * 选择系统图片Request Code
     */
    public static final int REQUEST_IMAGE = 112;

    private void selectQRCode() {
        Intent it = new Intent("image/*");
        startActivityForResult(it, REQUEST_IMAGE);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (data != null) {
                Uri uri = data.getData();
                getAnalyzeQRCodeResult(uri);
            }
        }
    }

    private void getAnalyzeQRCodeResult(Uri uri) {
        XQRCode.analyzeQRCode(getRealFilePath(getContext(), uri), analyzeCallback);
    }

    @Override
    public void onDestroyView() {
        //恢复设置
        CameraManager.FRAME_MARGIN_TOP = -1;
        super.onDestroyView();
    }

    /**
     * Try to return the absolute file path from the given Uri
     *
     * @param context
     * @param uri
     * @return the file path or null
     */
    public String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri)
            return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{
                    MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }





}
